package logic

import (
	"context"
	"errors"
	"shang/models/mysql"

	"shang/shangrpc/internal/svc"
	"shang/shangrpc/shangrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShangAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShangAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShangAddLogic {
	return &ShangAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShangAddLogic) ShangAdd(in *shangrpc.ShangAddRequest) (*shangrpc.ShangAddResponse, error) {
	// todo: add your logic here and delete this line
	shang := mysql.Shang{
		Title:   in.Title,
		Image:   in.Image,
		Price:   float64(in.Price),
		ClassId: int(in.ClassId),
	}
	mysql.DB.Debug().Create(&shang)
	if in.Title == shang.Title {
		return nil, errors.New("商品重复,禁止添加")
	}
	err := mysql.DB.Debug().Create(&shang).Error
	if err != nil {
		return nil, errors.New("添加失败")
	}

	class := mysql.Class{
		ClassName: in.ClassName,
	}

	if in.ClassId != 0 {
		mysql.DB.Debug().Create(class)
	}

	return &shangrpc.ShangAddResponse{
		ShangId: int64(shang.ID),
	}, nil
}
